//
//  NavigationTitleView.swift
//  YOKO
//
//  Created by vivi on 16/5/27.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import SnapKit

class NavigationTitleView: UIView {
    
    private var __expandImageView: UIImageView!
    private var __titleLabel: UILabel!
    private var __maxWords: Int = 10 //表示titleLabel的最大字数容量
    
    var maxWords: Int {
        get { return __maxWords }
        set {
            __maxWords = max(maxWords, 1)
            if let text = __titleLabel.text {
                if (text.characters.count > __maxWords) {
                    __titleLabel.text = text.substringToIndex(text.startIndex.advancedBy(maxWords))
                }
            }
            //self.sizeToFit()
        }
    }
    
    var title: String {
        get {
            return __titleLabel.text ?? ""
        }
        set {
            if (newValue.characters.count <= __maxWords) {
                __titleLabel.text = newValue
            }
            else {
                __titleLabel.text = newValue.substringToIndex(newValue.startIndex.advancedBy(__maxWords))
            }
            //self.sizeToFit()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        __expandImageView = UIImageView(image: UIImage(named: "icon_展开"))
        __expandImageView.frame = CGRectMake(0.0, 0.0, 20.0, 10.0)
        __expandImageView.contentMode = .ScaleAspectFit
        
        __titleLabel = UILabel(frame: CGRectZero)
        __titleLabel.font = UIFont.systemFontOfSize(19.0)
        __titleLabel.textColor = UIColor.whiteColor()
        __titleLabel.backgroundColor = UIColor.clearColor()
        
        self.addSubview(__expandImageView)
        self.addSubview(__titleLabel)
        __titleLabel.snp_makeConstraints {
            make in
            make.center.equalTo(self)
        }
        __expandImageView.snp_makeConstraints {
            make in
            make.size.equalTo(CGSizeMake(20.0, 10.0))
            make.left.equalTo(__titleLabel.snp_right).offset(2.0)
            make.bottom.equalTo(__titleLabel).offset(-5)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("\(#function) --> Cannot init with init?(coder aDecoder: NSCoder)")
    }
    
    override func sizeToFit() {
        print("\(#function)")
        __titleLabel.sizeToFit()
        
        let newWidth = (2 + __expandImageView.frame.width) * 2 + __titleLabel.frame.width
        let newHeight = max(__expandImageView.frame.height, __titleLabel.frame.height)
        
        self.frame.size =  CGSizeMake(newWidth, newHeight)
        __titleLabel.center = CGPointMake(newWidth / 2.0, newHeight / 2.0)
        __expandImageView.frame.origin = CGPointMake(__titleLabel.frame.origin.x + __titleLabel.frame.width + 2.0, newHeight / 3.0)
    }
}
